{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## **两种写法的对比**\n",
    "\n",
    "| **写法**                          | **适用场景**                     | **优点**                                                                 | **缺点**                                                                 |\n",
    "|-----------------------------------|----------------------------------|--------------------------------------------------------------------------|--------------------------------------------------------------------------|\n",
    "| `features = data.drop('target', axis=1)` | `data` 是 **Pandas DataFrame**   | - 代码简洁，直接操作 DataFrame。<br>- 适用于数据已经是 DataFrame 的情况。 | - 仅适用于 Pandas DataFrame，不适用于 JSON 字典或其他数据结构。          |\n",
    "| `features = np.array(data['features'])`  | `data` 是 **JSON 字典**          | - 适用于从 JSON 文件读取的数据。<br>- 灵活处理嵌套列表结构。             | - 需要手动提取特征和目标变量，代码稍显冗长。<br>- 需要额外转换为 NumPy 数组。 |\n",
    "\n",
    "---\n",
    "\n",
    "### **示例代码对比**\n",
    "\n",
    "#### **写法 1：`data` 是 Pandas DataFrame**\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "# 假设 data 是一个 Pandas DataFrame\n",
    "data = pd.DataFrame({\n",
    "    'feature1': [1, 2, 3],\n",
    "    'feature2': [4, 5, 6],\n",
    "    'target': [10, 20, 30]\n",
    "})\n",
    "\n",
    "# 提取特征和目标变量\n",
    "features = data.drop('target', axis=1)  # 删除 'target' 列，得到特征\n",
    "target = data['target']                # 提取 'target' 列，得到目标变量\n",
    "\n",
    "## **写法 2：`data` 是 JSON 字典**\n",
    "\n",
    "### **适用场景**\n",
    "- 当数据是从 **JSON 文件** 或其他嵌套列表结构中读取时。\n",
    "\n",
    "### **代码实现**\n",
    "```python\n",
    "import json\n",
    "import numpy as np\n",
    "\n",
    "# 假设 data 是从 JSON 文件读取的字典\n",
    "data = {\n",
    "    \"features\": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n",
    "    \"target\": [10, 20, 30]\n",
    "}\n",
    "\n",
    "# 提取特征和目标变量\n",
    "features = np.array(data['features'])  # 转换为 NumPy 数组\n",
    "target = np.array(data['target'])      # 转换为 NumPy 数组\n",
    "\n",
    "print(features)\n",
    "print(target)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "from typing import Tuple\n",
    "import numpy as np\n",
    "from sklearn.metrics import accuracy_score\n",
    "import pandas as pd\n",
    "from sklearn.base import BaseEstimator\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.neural_network import *\n",
    "\n",
    "\n",
    "def read_data(file_path: str) -> Tuple[pd.DataFrame, pd.Series]:\n",
    "    #TODO\n",
    "    data = pd.read_csv(file_path)\n",
    "    x = data.drop('target',axis=1) # 提取特征数据，排除'target'列\n",
    "    y = data['target'] # 提取目标变量数据\n",
    "    return x,y\n",
    "def train(X_train: pd.DataFrame, y_train: pd.Series) -> BaseEstimator:\n",
    "    #TODO\n",
    "    # 初始化多层感知机分类器\n",
    "    model = MLPClassifier(max_iter=500,hidden_layer_sizes=(500,300),random_state=42,alpha=0.001,learning_rate_init=0.001)\n",
    "    model.fit(X_train,y_train)\n",
    "    return model\n",
    "\n",
    "def save_model(model: BaseEstimator, file_path: str) -> None:\n",
    "    #TODO\n",
    "    with open(file_path,'wb') as f:\n",
    "         # 使用pickle模块将模型对象序列化为二进制数据并写入文件\n",
    "        pickle.dump(model,f)\n",
    "\n",
    "def load_model(file_path: str) -> BaseEstimator:\n",
    "    #TODO\n",
    "    with open(file_path,'rb') as f:\n",
    "        # 使用pickle模块加载模型,fanc:将二进制数据反序列化为Python对象\n",
    "        model = pickle.load(f)\n",
    "    return model\n",
    "\n",
    "\n",
    "def main() -> None:\n",
    "    features, targets = read_data('train_data.csv')\n",
    "    X_train, X_test, y_train, y_test = train_test_split(\n",
    "        features, targets, test_size=0.2, random_state=42)\n",
    "    model = train(X_train, y_train)\n",
    "    file_path = 'model.pkl'\n",
    "    save_model(model, file_path)\n",
    "    model = load_model(file_path)\n",
    "    y_pred = model.predict(X_test)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorchgpu",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.9.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
